package net.cmkj.mine.interceptor;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import net.cmkj.mine.bean.ModuleUser;
import net.cmkj.mine.bean.SysRole;
import net.cmkj.mine.bean.SysUser;
import net.cmkj.mine.util.SessionKit;

import java.util.List;

public class MineInterceptor implements Interceptor{
    public void intercept(Invocation inv) {
        //SysUser sysUser = IWebUtils.getCurrentSysUser(inv.getController().getRequest());
        SysUser user = SessionKit.getCurrentLoginUser();
        Long moduleid = (Long) inv.getArg(2);
        if (user != null && moduleid != null) {
            List<SysRole> roles = SysRole.dao.getSysRoleIdList(user.getId());
            if (roles == null) {
                inv.setArg(5," and  1=2  order by id desc");
            } else {
                if (!hasAdmin(roles)) {
                    ModuleUser moduleUser = ModuleUser.dao.findFirst("SELECT * FROM `module_user` where `user` = "+user.getId()+" and module = " + moduleid);
                    if(moduleUser==null){//仅自己
                        inv.setArg(5,"  and t.createuser = "+user.getId()+" order by id desc");
                    }else{
                        Integer type = moduleUser.getType();
                        if(type==1){//本部门
                            inv.setArg(5,"  and (t.deptid = "+user.getDeptid()+" or t.deptid in (select t.id from sys_dept t where find_in_set("+user.getDeptid()+", ancestors)))  order by id desc");
                        }else if(type==2){//全公司
                            inv.setArg(5,"  order by id desc");
                        }else {//仅自己
                            inv.setArg(5,"  and t.createuser = "+user.getId()+" order by id desc");
                        }
                    }
                }
            }
        } else {
            inv.setArg(5," and  1=2  order by id desc");
        }
        inv.invoke();
    }

    protected boolean hasAdmin(List<SysRole> roles) {
        boolean flag = false;
        for (SysRole sysRole : roles) {
            int roleId = sysRole.getId();
            if (roleId == 1) {
                flag = true;
                break;
            }
        }
        return flag;
    }
}
